#include "camera_lens_ctrl.h"

CameraLensCtrl::CameraLensCtrl():
	maxFocus(0),
	curFocus(0)
{
	
}

bool CameraLensCtrl::connectSerialPort(const QString& serialName)
{
	bool ok = lens.open(serialName);
	if (!ok) {
		return false;
	}

	uchar lenID;
	ushort curFocus, maxFocus, curAperture;
	QVector<ushort> focusRange, apertureRange;
	lens.systemInit(lenID, curFocus, focusRange, maxFocus, curAperture, apertureRange);

	this->maxFocus = maxFocus;

	this->curFocus = 0;
	lens.setFocusPos(this->curFocus);

	return true;
}

bool CameraLensCtrl::adjust(const FocusAction& action)
{
	if (action.action == FocusAction::STOP) {
		return false;
	}

	if (action.action == FocusAction::SEEK) {
		curFocus = action.value;
		lens.setFocusPos(curFocus);
		return false;
	}

	if (action.value == 0) {
		return false;
	}

	int newFocus = curFocus;
	if (action.action == FocusAction::FORWARD) {
		newFocus += action.value;
	} else if (action.action == FocusAction::BACKWARD) {
		newFocus -= action.value;
	}

	bool isBorder = false;
	if (newFocus <= 0) {
		newFocus = 0;
		isBorder = true;
	} else if (newFocus >= maxFocus) {
		newFocus = maxFocus;
		isBorder = true;
	}

	lens.setFocusPos(newFocus);
	curFocus = newFocus;

	return isBorder;
}

int CameraLensCtrl::getPos()
{
	return curFocus;
}

int CameraLensCtrl::getMaxFocusPos()
{
	return maxFocus;
}


